package com.wy.mavenUtil;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import sun.swing.FilePane;

import java.io.*;
import java.nio.file.*;
import java.util.List;

// 这种方式是解析pom.xml，然后将解析所依赖的包进行一个拷贝到指定的目录，但是有一个问题，无法去处理依赖冲突。
public class PomDependencyExporter {
    private final String localRepositoryPath;
    private final String outputDirectory;

    public PomDependencyExporter(String localRepositoryPath, String outputDirectory) {
        this.localRepositoryPath = localRepositoryPath;
        this.outputDirectory = outputDirectory;
    }

    public void exportDependencies(String pomPath) throws IOException, XmlPullParserException {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        Model model;
        try (FileReader fileReader = new FileReader(pomPath)) {
            model = reader.read(fileReader);
        }

        // 获取所有依赖
        List<Dependency> dependencies = model.getDependencies();

        // 创建输出目录
        Files.createDirectories(Paths.get(outputDirectory));

        // 处理依赖
        for (Dependency dependency : dependencies) {
            if (dependency.getVersion() == null) {
                // 递归查找版本信息
                String version = findVersionFromParentChain(model, dependency);
                if (version != null) {
                    dependency.setVersion(version);
                } else {
                    System.err.println("无法找到依赖的版本: " + dependency.getArtifactId());
                    continue;
                }
            }
            copyDependency(dependency);
        }
    }

    private String findVersionFromParentChain(Model currentModel, Dependency dependency) throws IOException, XmlPullParserException {
        // 先在当前模型的 dependencyManagement 中查找
        String version = findVersionFromParent(currentModel, dependency);
        if (version != null) {
            return version;
        }

        // 如果当前模型有父模型，则继续查找
        Parent parent = currentModel.getParent();
        if (parent != null) {
            String parentPomPath = buildParentPomPath(parent);
            if (parentPomPath != null) {
                try (FileReader parentFileReader = new FileReader(parentPomPath)) {
                    MavenXpp3Reader reader = new MavenXpp3Reader();
                    Model parentModel = reader.read(parentFileReader);
                    // 递归查找父模型
                    return findVersionFromParentChain(parentModel, dependency);
                } catch (IOException e) {
                    System.err.println("无法读取父 pom 文件: " + parentPomPath);
                    return null;
                }
            }
        }
        return null;
    }

    private String buildArtifactPath(Dependency dependency) {
        return String.format("%s/%s/%s/%s-%s.jar",
                dependency.getGroupId().replace('.', '/'),
                dependency.getArtifactId(),
                dependency.getVersion(),
                dependency.getArtifactId(),
                dependency.getVersion()
        );
    }

    private String buildParentPomPath(Parent parent) {
        String filePath = String.format("%s/%s/%s/%s/%s-%s.pom",
                localRepositoryPath,
                parent.getGroupId().replace('.', '/'),
                parent.getArtifactId(),
                parent.getVersion(),
                parent.getArtifactId(),
                parent.getVersion()
        );
        File file = new File(filePath);
        String lowFileName1 = file.getName().toLowerCase();
        File[] files = file.getParentFile().listFiles();
        String realFilePath = "";
        boolean flag = false;
        for (File file1 : files) {
            String reallyLowFileName = file1.getName().toLowerCase();
            if (reallyLowFileName.equals(lowFileName1)) {
                flag = true;
                realFilePath = file1.getAbsolutePath();
                break;
            }
        }
        if (flag) {
            return realFilePath;
        } else {
            return null;
        }
    }

    private String findVersionFromParent(Model parentModel, Dependency dependency) {
        if (parentModel.getDependencyManagement() != null) {
            for (Dependency managedDep : parentModel.getDependencyManagement().getDependencies()) {
                if (managedDep.getGroupId().equals(dependency.getGroupId()) &&
                        managedDep.getArtifactId().equals(dependency.getArtifactId())) {
                    return managedDep.getVersion();
                }
            }
        }
        return null;
    }

    private void copyDependency(Dependency dependency) {
        try {
            String artifactPath = buildArtifactPath(dependency);
            Path source = Paths.get(localRepositoryPath, artifactPath);
            Path target = Paths.get(outputDirectory, source.getFileName().toString());

            Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("已复制: " + dependency.getArtifactId());
        } catch (IOException e) {
            System.err.println("复制失败 " + dependency.getArtifactId() + ": " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String localRepo = "D:\\study_soft\\maven\\apache-maven-3.6.1\\apache-maven-3.6.1\\repo"; // 替换为实际的Maven本地仓库路径
        String outputDir = "C:\\Users\\wy\\Desktop\\新建文件夹 (2)\\lib"; // 替换为实际的输出目录
        String pomPath = "C:\\Users\\wy\\Desktop\\新建文件夹 (2)\\pom.xml"; // 替换为实际的pom文件路径

        PomDependencyExporter exporter = new PomDependencyExporter(localRepo, outputDir);
        try {
            exporter.exportDependencies(pomPath);
            System.out.println("Dependencies exported successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}